package cn.iocoder.yudao.adminserver.franky.proxy;

import org.junit.jupiter.api.Test;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Description:
 * @Author: franky
 * @CreateDate: 2021/5/20 4:10 下午
 * @Version: 1.0
 */
public class CostTimeInvocationHandler implements InvocationHandler {

    private Object target;

    public CostTimeInvocationHandler (Object target) {
        this.target = target;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Long start = System.nanoTime();
        Object result = method.invoke(this.target, args);
        long end = System.nanoTime();
        System.out.println(this.target.getClass()+"的方法" + method.getName() + "耗时（纳秒）: " + (end - start));
        return result;
    }

    public static <T> T createProxy(Object target, Class<T> interfaces) {
        if (!interfaces.isInterface()) {
            throw new IllegalStateException("代理的类必须是接口类型！");
        } else if(!interfaces.isAssignableFrom(target.getClass())) {
            throw new IllegalStateException(target.getClass().getName() + "必须是"+interfaces.getName()+"的实现类！");
        }
        return (T) Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), new CostTimeInvocationHandler(target));
    }
}
